use log::{info, trace, warn,error};

use crate::app_config::AppConfig;
use std::{
    error::Error,
    path::{Path, PathBuf},
    process::{self, Output},
};

pub fn get_srt_file(video_file: &str) -> Result<PathBuf, Box<dyn Error + 'static>> {
    let file_path = Path::new(video_file);
    let srt_file = file_path
        .file_name()
        .expect("get file name failed!")
        .to_str()
        .expect("get file name failed!")
        .replace(file_path.extension().unwrap().to_str().unwrap(), "srt");
    let srt_file = file_path.with_file_name(srt_file);
    Ok(srt_file)
}

pub fn extract_audio_impl(video_file: &str, audio_file: &str) -> Result<(), Box<dyn Error>> {
    let config = AppConfig::get();
    
    let mut cmdargs = vec!["-i", video_file, "-vn -ar 16000", audio_file];
    let ffmpeg_conf_path = config.ffmpeg_path().to_string();
    let mut ffmpeg_path:PathBuf;
    if ffmpeg_conf_path.is_empty(){
        if check_ffmpeg_installed(){
            ffmpeg_path=PathBuf::from("ffmpeg");
        }else{
            return Err("ffmpeg文件路径未配置，且在环境中未找到可执行的ffmpeg文件".into());
        }
    }else{
        ffmpeg_path = PathBuf::from(ffmpeg_conf_path);
        if cfg!(target_os = "windows") {
            ffmpeg_path.push("ffmpeg.exe");
            let ffmpeg_file_path = Path::new(&ffmpeg_path);
            let ffmpeg_exists = ffmpeg_file_path.exists();
            if !ffmpeg_exists {
                return Err("ffmpeg文件不存在".into());
            }
        }
        else if cfg!(target_os = "linux") {
            ffmpeg_path.push("ffmpeg");
            if !ffmpeg_path.exists() {
                return Err("ffmpeg文件不存在".into());
            }
        }
    }
    
    cmdargs.insert(0, ffmpeg_path.to_str().unwrap());
    
    let mut cmd_output:Result<Output,std::io::Error>=Err(std::io::Error::from(std::io::ErrorKind::Other));
    if cfg!(target_os="windows"){
        cmd_output = process::Command::new("powershell")
        .args(cmdargs.as_slice())
        .output();
    }else if cfg!(target_os="linux"){
        let mut cmd = process::Command::new("sh");
        cmd.arg("-c");
        cmd.arg(cmdargs.join(" "));
        trace!("cmd:{:?}",cmd);
        cmd_output=cmd.output();
    }
    

    match cmd_output {
        Ok(output) => {
            info!("提取音频中. 请稍等...");
            if output.status.success() {
                info!("提取音频成功");
                Ok(())
            } else {
                error!("提取音频失败");
                trace!("{}",String::from_utf8_lossy(&output.stdout));
                error!("{}", String::from_utf8_lossy(&output.stderr));
                Err("提取音频失败".into())
            }
        }
        Err(e) => {
            error!("提取音频失败:{}", e);
            Err(e.into())
        }
    }
    // Ok(())
}

fn check_ffmpeg_installed()->bool{
    let out= process::Command::new("ffmpeg").arg("-version").output();

    match out {
        Ok(output)=>{
            if output.status.success(){
                true
            }else{
                info!("std:{}",String::from_utf8_lossy(&output.stdout));
                warn!("err:{}",String::from_utf8_lossy(output.stderr.as_slice()));
                false
            }
        },
        Err(err)=>{
            error!("exception occured when check ffmpeg installed, ex is: {}",err);
            false
        },
    }
}
mod test{
    #[allow(unused_imports)]
    use super::check_ffmpeg_installed;

    #[test]
    fn check_ffmpeg_installed_test(){
       let is_install=  check_ffmpeg_installed();
       println!("ffmpeg installed: {}",is_install);
    }
}
